package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.api.R;
import com.itheima.common.Result;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.UserName;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    //请求 URL: http://localhost:8080/user/sendMsg
    //请求方法: POST
    @PostMapping("/sendMsg")
    public Result sendMsg(@RequestBody User user, HttpServletRequest req) {

        String phone = user.getPhone();
        //生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code={}", code);

        HttpSession session = req.getSession();
        session.setAttribute(phone, code);
        return Result.success(code);

    }

    @PostMapping("/login")
    public Result isLogin(@RequestBody Map<String, String> map, HttpServletRequest req) throws UnsupportedEncodingException {

        String getCode = map.get("code");
        String getPhone = map.get("phone");

        HttpSession session = req.getSession();

        String SessionCode = (String) session.getAttribute(getPhone);
        ;

        if (getCode == null || SessionCode == null || !SessionCode.equals(getCode)) {
            return Result.error("登陆失败");
        }

        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, getPhone);
        User one = userService.getOne(lqw);
        if (one == null) {
            one = new User();
            one.setName(UserName.getUsername());
            one.setPhone(getPhone);
            userService.save(one);
        }

        session.removeAttribute(getPhone);
        session.setAttribute("user", one.getId());
        return Result.success("登陆成功");
    }

//    请求 URL: http://localhost:8080/user/loginout
//    请求方法: POST
    @PostMapping("/loginout")
    public Result loginOut(HttpServletRequest req ){

        HttpSession session = req.getSession();

        session.invalidate();

        return Result.success("退出成功");

    }

}
